<?php

namespace App\Http\Controllers\Kindeditor;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Carbon\Carbon;
use Image;

class UploadController extends Controller
{

    /**
     * kindeditor上传文件
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $file = $request->file('imgFile');
        if ($file->isValid()) {
            if (in_array($file->getClientOriginalExtension(), ['gif', 'jpg', 'jpeg', 'png', 'bmp'])) {
                $filename = md5($file->getClientOriginalName() . Carbon::now()->toDateTimeString() . mt_rand(1,
                            9999)) . '.' . $file->getClientOriginalExtension();
                $filepath = public_path() . '/uploads/' . Carbon::now()->toDateString();
                if (!file_exists($filepath)) {
                    mkdir($filepath);
                }
                if ($request->input('type') == 'brand') {
                    Image::make($file)->resize('160', '100')->save($filepath . '/' . $filename);
                } elseif ($request->input('type') == 'product') {
                    Image::make($file)->resize('400', '400')->save($filepath . '/' . $filename);
                } elseif ($request->input('type') == 'ads') {
                    Image::make($file)->resize('848', '356')->save($filepath . '/' . $filename);
                } else {
                    $file->move($filepath, $filename);
                }
                $uploadFileUrl = strstr($filepath, '/uploads') . '/' . $filename;
                return response()->json(['error' => 0, 'url' => $uploadFileUrl]);
            } else {
                return response()->json(['error' => 1, 'message' => '仅允许"gif","jpg","jpeg","png","bmp"格式文件']);
            }
        } else {
            return response()->json(['error' => 1, 'message' => '上传失败']);
        }
    }

}
